import os
import fileValidation as fv
import global_objects as go
import structures as s
import generate as g

#currDir = "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/PSP/DataGenerator"

def sqlGeneration(fname):
    """ This function generates data according to the data model provided in a file as an argument.
        It writes the generated data in an output file in SQL format."""

    del fv.tables[0:]
    fv.split_methadata(fname)
    s.getTables()
    s.getColumns()
    s.getTypes()
    s.getArgs()

    currDir = os.path.abspath(os.getcwd())
    currDir = currDir.replace("\\","/") + "/htdocs/PSP/DataGenerator"
    f = open(currDir + '/files/readyData.txt', 'w')
    
    tblsCnt = len(go.tbls)
    # goes through each table
    for t in range(0, tblsCnt):
        tbl_values = []

        index = 0
        # for each table goes through each type
        for each_type in go.types[t]:
            type_values = []

            if (each_type == 'numeric'):
                # for each table generates numeric values per columns
                for r in range(0, go.tbls[t][1]):
                    type_values.append(str(g.genNumeric(go.args[t][index])))    #f.write(str(g.genNumeric(go.args[t][index])) + ", ")
                go.pk = []
                index += 1
                tbl_values.append(type_values)

            if (each_type == 'string'):
                # for each table generates string values per columns
                for r in range(0, go.tbls[t][1]):
                    type_values.append(repr(g.genString(go.args[t][index])))    #f.write(g.genString(go.args[t][index]) + ", ")
                index += 1
                tbl_values.append(type_values)

            if (each_type == 'date'):
                # for each table generates date values per columns
                for r in range(0, go.tbls[t][1]):
                    type_values.append(repr(g.genDate()))                             #f.write(g.genDate() + ", ")
                index += 1
                tbl_values.append(type_values)

        tbl_values_length = len(tbl_values)

        # writes to file generated records
        f.write("/* inserting generated records for %s table */\n" %go.tbls[t][0].upper())
        for r in range(0, go.tbls[t][1]):

            f.write("insert into %s(" %go.tbls[t][0])
            f.write(', '.join(go.clmns[t]) + ") values(")
            for c in range(0, tbl_values_length):
                f.write(tbl_values[c][r] + ", ")

            f.seek(-2, 1)
            f.write(")\n")
        
        f.write("\n")    

        #print tbl_values
        #print "\n"
        
    f.close()
